<!---
	TEMPLATE: userForm_process.cfm
	AUTHOR: Matt Woodward (mpwoodward@gmail.com)
	DATE: 2/20/2005
	PURPOSE: processing page for user form; interacts with Hibernate in CFML
	CHANGE HISTORY:
		* 2/20/2005: template created (Matt Woodward)
		* 2/21/2005: template updated to handle "update" actions
						(Matt Woodward)
		* 27/06/2006: changed code to use more of a 3.x style (Mark Mandel)
--->

<!--- set defaults for form data --->
<cfparam name="form.firstName" type="string" default="" />
<cfparam name="form.lastName" type="string" default="" />
<cfparam name="form.email" type="string" default="" />
<cfparam name="form.action" type="string" default="" />

<!--- make sure we have the required form data --->
<cfif form.firstName EQ "" OR form.lastName EQ "" OR form.email EQ ""
	OR form.action EQ "">
	<script type="text/javascript">
		alert("We're sorry, required data was not passed to this page.\n
				Please try again");
		history.go(-1);
	</script>

	<cfabort />
</cfif>

<cfscript>
	// get Hibernate session factory

	// open a session and start the transaction
	mySession = application.sessionFactory.getCurrentSession();
	tx = mySession.beginTransaction();

	// take appropriate action based on form's action value
	switch(form.action) {
		case "Add":
			// instantiate a User object with the form data and persist it
			user = application.hibernateFactory.create("User").init(form.firstName,
																	form.lastName,
																	form.email);

			mySession.save(user);
			break;

		case "Update":
		
			// get the user - have to use a serialisable object as key
			//some way to wrap the need for a serialisable object?
			id = createObject("java", "java.lang.Integer").init(form.id);
			user = mySession.get("User", id);

			// set user data
			user.setFirstName(form.firstName);
			user.setLastName(form.lastName);
			user.setEmail(form.email);

			// update the user
			mySession.update(user);
			break;

		case "Delete":
			// get the user - have to use a serialisable object as key
			//some way to wrap the need for a serialisable object?		
			id = createObject("java", "java.lang.Integer").init(form.id);
			user = mySession.get("User", id);

			// delete the user
			mySession.delete(user);
			break;
	}

	// commit the transaction
	tx.commit();
</cfscript>

<html>
<head>
	<title>Process User Form</title>
</head>
<body>
	<h3>Process User Form</h3>

	<cfswitch expression="#form.action#">
		<cfcase value="Add">
			<p>Hibernate successfully persisted the new User object.</p>
		</cfcase>

		<cfcase value="Update">
			<p>Hibernate successfully persisted the updated User object.</p>
		</cfcase>

		<cfcase value="Delete">
			<p>Hibernate successfully deleted the User from the database.</p>
		</cfcase>
	</cfswitch>

	<ul>
		<li><a href="index.cfm">Main Menu</a></li>
		<li><a href="userForm.cfm">Add User</a></li>
	</ul>
</body>
</html>
